package scripts

import (
	"bytes"
	"github.com/jweny/pocassist/pkg/util"
	"regexp"
	"strconv"
	"strings"
)

var eximPattern = regexp.MustCompile(`Exim (4\.88|4\.89)`)

// EximUaf
func EximUaf(args *ScriptScanArgs) (*util.ScanResult, error) {
	for _, port := range []int{25, 26, 465, 587} {
		target := args.Host+":"+strconv.Itoa(port)
		payload := "EHLO test\n"
		resp, err := util.TcpSend(target, []byte(payload))
		if port == 465 {
			resp, err = util.TcpTlsSend(target, []byte(payload))
		}
		if err != nil {
			continue
		}

		strResponse := string(resp)
		if strings.Contains(strResponse, "Exim") && (strings.Contains(strResponse, "4.88") ||
			strings.Contains(strResponse, "4.89")) && !strings.Contains(strResponse, "4.89.1") &&
			!strings.Contains(strResponse, "4.89_1") {
			groups := eximPattern.Find(resp)
			if len(groups) > 0 {
				if bytes.Contains(resp, []byte("250-CHUNKING")) {
					return util.VulnerableTcpOrUdpResult(target, string(groups),
						[]string{payload}, []string{string(resp)}),nil
				}
			}
			}
	}
	return &util.InVulnerableResult, nil
}

func init() {
	ScriptRegister("poc-go-exim-cve-2017-16943-uaf", EximUaf)
}
